#include "logmanage.h"

LogManage::LogManage(QWidget *parent) : QWidget(parent)
{
    m_pSqliteManage = new SqliteManage;
    if (!m_pSqliteManage->openDatabase("C:/Users/shafl/Desktop/FrameWork/test.db")) {
        QMessageBox::critical(this, "错误", "数据库连接失败：" + m_pSqliteManage->lastError());
    }
    initUI();
    initConnections();
}

LogManage::~LogManage()
{
}

void LogManage::initUI()
{
    // 创建布局
    QVBoxLayout* mainLayout = new QVBoxLayout(this);

    // 创建筛选区域
    QHBoxLayout* filterLayout = new QHBoxLayout();

    // 时间选择
    QLabel* startTimeLabel = new QLabel("开始时间:", this);
    m_startTimeEdit = new QDateTimeEdit(this);
    m_startTimeEdit->setDateTime(QDateTime::currentDateTime().addDays(-1));
    m_startTimeEdit->setDisplayFormat("yyyy-MM-dd HH:mm:ss");

    QLabel* endTimeLabel = new QLabel("结束时间:", this);
    m_endTimeEdit = new QDateTimeEdit(this);
    m_endTimeEdit->setDateTime(QDateTime::currentDateTime());
    m_endTimeEdit->setDisplayFormat("yyyy-MM-dd HH:mm:ss");

    // 日志类型筛选
    QLabel* logTypeLabel = new QLabel("日志类型:", this);
    m_logTypeCombo = new QComboBox(this);
    m_logTypeCombo->addItem("所有日志", -1);
    m_logTypeCombo->addItem("系统日志", SYSTEM_LOG);
    m_logTypeCombo->addItem("操作日志", OPERATION_LOG);
    m_logTypeCombo->addItem("告警日志", ALARM_LOG);
    m_logTypeCombo->addItem("异常日志", EXCEPTION_LOG);

    // 关键词筛选
    QLabel* keywordLabel = new QLabel("关键词:", this);
    m_keywordEdit = new QLineEdit(this);

    // 查询按钮
    m_queryButton = new QPushButton("查询", this);

    // 导出按钮
    m_exportButton = new QPushButton("导出", this);

    // 添加到筛选布局
    filterLayout->addWidget(startTimeLabel);
    filterLayout->addWidget(m_startTimeEdit);
    filterLayout->addWidget(endTimeLabel);
    filterLayout->addWidget(m_endTimeEdit);
    filterLayout->addWidget(logTypeLabel);
    filterLayout->addWidget(m_logTypeCombo);
    filterLayout->addWidget(keywordLabel);
    filterLayout->addWidget(m_keywordEdit);
    filterLayout->addWidget(m_queryButton);
    filterLayout->addWidget(m_exportButton);

    // 创建日志表格
    m_logModel = new QStandardItemModel(0, 7, this);
    m_logModel->setHorizontalHeaderLabels({"日志ID", "时间戳", "日志类型", "日志等级", "日志内容", "用户ID", "设备ID"});

    m_logTableView = new QTableView(this);
    m_logTableView->setModel(m_logModel);
    m_logTableView->setEditTriggers(QAbstractItemView::NoEditTriggers);
    m_logTableView->setSelectionBehavior(QAbstractItemView::SelectRows);
    m_logTableView->setSelectionMode(QAbstractItemView::SingleSelection);
    m_logTableView->horizontalHeader()->setStretchLastSection(true);
    m_logTableView->setAlternatingRowColors(true);

    // 添加到主布局
    mainLayout->addLayout(filterLayout);
    mainLayout->addWidget(m_logTableView);

    setLayout(mainLayout);
}

void LogManage::initConnections()
{
    connect(m_queryButton, &QPushButton::clicked, this, &LogManage::onQueryButtonClicked);
    connect(m_exportButton, &QPushButton::clicked, this, &LogManage::onExportButtonClicked);
}

void LogManage::onQueryButtonClicked()
{
    // 获取筛选条件
    QDateTime startTime = m_startTimeEdit->dateTime();
    QDateTime endTime = m_endTimeEdit->dateTime();
    int typeIndex = m_logTypeCombo->currentData().toInt();
    LogType logType = static_cast<LogType>(typeIndex);
    QString keyword = m_keywordEdit->text();

    // 查询日志
    LogClass* logManager = LogClass::getInstance();
    QVector<QVector<QVariant>> logs = logManager->queryLogs(m_pSqliteManage, startTime, endTime, logType, keyword);

    // 更新表格
    updateLogTable(logs);
}

void LogManage::updateLogTable(const QVector<QVector<QVariant>>& logs)
{
    // 清空表格
    m_logModel->removeRows(0, m_logModel->rowCount());

    // 添加日志数据
    for (const auto& row : logs) {
        QList<QStandardItem*> items;
        for (const auto& value : row) {
            QStandardItem* item = new QStandardItem(value.toString());
            items.append(item);
        }
        m_logModel->appendRow(items);
    }
}

void LogManage::onExportButtonClicked()
{
    // 获取筛选条件
    QDateTime startTime = m_startTimeEdit->dateTime();
    QDateTime endTime = m_endTimeEdit->dateTime();
    int typeIndex = m_logTypeCombo->currentData().toInt();
    LogType logType = static_cast<LogType>(typeIndex);
    QString keyword = m_keywordEdit->text();

    // 获取保存路径
    QString filePath = QFileDialog::getSaveFileName(
        this, "导出日志",
        QCoreApplication::applicationDirPath() + "/logs/log_export_" +
        QDateTime::currentDateTime().toString("yyyyMMdd_HHmmss"),
        "CSV文件 (*.csv);;文本文件 (*.txt)"
    );

    if (filePath.isEmpty()) {
        return;
    }

    // 判断文件类型
    bool isCsv = filePath.endsWith(".csv", Qt::CaseInsensitive);

    // 导出日志
    LogClass* logManager = LogClass::getInstance();
    if (logManager->exportLogs(m_pSqliteManage, filePath, startTime, endTime, logType, keyword, isCsv)) {
        QMessageBox::information(this, "成功", "日志导出成功！");
    } else {
        QMessageBox::critical(this, "失败", "日志导出失败！");
    }
}
